package com.caiyi.financial.nirvana.sms.filter;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.caiyi.financial.nirvana.sms.entity.SmsUser;
import com.caiyi.financial.nirvana.sms.enums.ReturnCodeEnum;
import com.caiyi.financial.nirvana.sms.util.Constant;
import com.youyu.common.api.Result;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class InterceptorConfig implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(InterceptorConfig.class);


    @Autowired
    private DefaultKaptcha captchaProducer;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        SmsUser smsUser = (SmsUser) request.getSession().getAttribute(Constant.SESSION_CUSTOMER_USER);
        if(null != smsUser){
            return true;
        }
        this.sendJsonMessage(response);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }


    /**
     * 将某个对象转换成json格式并发送到客户端
     * @param response
     * @throws Exception
     */
    public void sendJsonMessage(HttpServletResponse response) throws Exception {
        response.setContentType("application/json; charset="+Constant.CHARSET_UTF8);
        response.setCharacterEncoding(Constant.CHARSET_UTF8);
        Result Result = new Result();
        Result.setCode(ReturnCodeEnum.NOT_LOGIN_ERROR.code);
        Result.setDesc(ReturnCodeEnum.NOT_LOGIN_ERROR.desc);
        PrintWriter writer = response.getWriter();
        writer.print(JSONObject.toJSONString(Result, SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteDateUseDateFormat));
        writer.close();
        response.flushBuffer();
    }
}
